package cn.bdqn.pn.controller.order;

import cn.bdqn.pn.pojo.base.City;
import cn.bdqn.pn.pojo.commodity.Commodity;
import cn.bdqn.pn.pojo.commodity.Sku;
import cn.bdqn.pn.pojo.order.ChildOrder;
import cn.bdqn.pn.pojo.order.MainOrder;
import cn.bdqn.pn.pojo.schedule.Commoditysession;
import cn.bdqn.pn.pojo.schedule.Place;
import cn.bdqn.pn.pojo.user.Admin;
import cn.bdqn.pn.service.base.CityService;
import cn.bdqn.pn.service.commodity.CommodityService;
import cn.bdqn.pn.service.commodity.SkuService;
import cn.bdqn.pn.service.order.ChildOrderService;
import cn.bdqn.pn.service.order.MainOrderService;
import cn.bdqn.pn.service.schedule.CommoditysessionService;
import cn.bdqn.pn.service.schedule.PlaceService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import sun.applet.Main;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.*;

/*@RestController*/
@Controller
@RequestMapping("/mainOrder")
public class MainOrderController {

    @Autowired
    ChildOrderService childOrderService;
    @Autowired
    private MainOrderService mainOrderService;
    @Autowired
    private SkuService skuService;
    @Autowired
    private CommodityService commodityService;
    @Autowired
    private CityService cityService;
    @Autowired
    private CommoditysessionService commoditysessionService;
    @Autowired
    private PlaceService placeService;

    /**
     * 查询订单信息
     * @param model
     * @param mainOrder
     * @param pageNo
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/selectMainOrderInfo")
    public String selectMainOrderInfo(Model model,MainOrder mainOrder,
                                      @RequestParam(value = "pageNo", defaultValue = "0") Integer pageNo,
                                      @RequestParam(value = "pageSize", defaultValue = "2") Integer pageSize) {
        Map map =mainOrderService.selectMainOrderInfoPackaging(mainOrder,pageNo,pageSize);
        model.addAttribute("status",mainOrder.getStatus());
        model.addAttribute("orderNum",mainOrder.getOrderNum());
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        String orderTime=null;
        String payTime=null;
        if(mainOrder.getOrderTime()!=null ){
             orderTime=simpleDateFormat.format(mainOrder.getOrderTime());
            model.addAttribute("orderTime",orderTime);
        }
        if(mainOrder.getPayTime()!=null){
             payTime=simpleDateFormat.format(mainOrder.getPayTime());
            model.addAttribute("payTime",payTime);
        }
        model.addAttribute("map",map);
        return  "Order_form";
    }

    /**
     * 根据订单号查询订单信息
     * @param model
     * @param mainOrder
     * @param pageNo
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/getOrder_detaileds")
    public String getOrder_detaileds(Model model,MainOrder mainOrder,
                                      @RequestParam(value = "pageNo", defaultValue = "0") Integer pageNo,
                                      @RequestParam(value = "pageSize", defaultValue = "2") Integer pageSize) {
        Map map=mainOrderService.selectMainOrderInfoPackaging(mainOrder,pageNo,pageSize);
        model.addAttribute("mainOrderId",mainOrder.getMainOrderId());
        model.addAttribute("map",map);
        Page<MainOrder> page= (Page<MainOrder>) map.get("orderInfo");
        //System.out.println("----------------------------------"+page.getContent().get(0).getOrderNum());
        Map mapChildOrder=childOrderService.findChidlOrderByOrderNum(page.getContent().get(0).getOrderNum());
        model.addAttribute("mapChildOrder",mapChildOrder);
        return  "Order_detaileds";
    }


    /**
     * 修改订单状态
     * @param
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updMainOrderStatusByMainOrderId",method = RequestMethod.POST)
    public Integer updMainOrderStatusByMainOrderId(Integer mainOrderId,String logisticsNum){
        return  mainOrderService.updMainOrderStatusByMainOrderId(mainOrderId,logisticsNum);
    }

    /**
     * 添加物流号
     * @param logisticsNum
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addMianOrderLogisticsNum",method = RequestMethod.POST)
    Integer addMianOrderLogisticsNum(Integer mainOrderId,String logisticsNum){
        System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++"+logisticsNum);
        return mainOrderService.addMianOrderLogisticsNum(mainOrderId,logisticsNum);
    }



    @RequestMapping(value = "/getOrderForm")
    public String getOrderForm(){
        return "order_form";
    }


    /**
     * 查询仅七天每天销售额
     * @return  销售额和对应日期
     */
    @ResponseBody
    @RequestMapping(value = "/selectPriceSum")
    public String selectPriceSumByDay(){
        System.out.println(JSONArray.toJSONString(mainOrderService.getPriceSumByDay()));
        return JSONArray.toJSONString(mainOrderService.getPriceSumByDay(),true);
    }


    /**
     * 统计销售总量
     */
    @ResponseBody
    @RequestMapping("/selectZongCount")
    public Integer selectZongCount(MainOrder mainOrder, HttpServletRequest request){
        Admin admin=(Admin)request.getSession().getAttribute("admin");  //获取用户对象
        mainOrder.setStatus(3);
        List<MainOrder> list=mainOrderService.getZongCount(mainOrder);
        Integer count=0;
        if(admin.getAdminId()==1){
            count=mainOrderService.getZongCount(mainOrder).size();
        }else{
            for(MainOrder mo:list){
                Integer skuId=mo.getSkuId();    //skuId
                Sku sku=skuService.getSkuById(skuId);   //sku对象
                Integer sessionId=sku.getSessionId(); // 场次id
                Commoditysession commoditysession=commoditysessionService.getById(sessionId);   //获取场次对象
                Integer placeId=commoditysession.getPlaceId();  //场地id
                Place place=placeService.findByPlace(placeId);
                Integer agentId=place.getAgentid();     //代理商id
                /*System.out.println("传入adminId:"+admin.getAdminId()+"查询代理商"+agentId);*/
                if(admin.getAdminId()==agentId){
                    count+=1;
                }
            }
        }
        return count;
    }

    //统计成交总金额
    @ResponseBody
    @RequestMapping("/selectTotalPrice")
    public Double selectTotalPrice(MainOrder mainOrder, HttpServletRequest request) {
        Admin admin=(Admin)request.getSession().getAttribute("admin");  //获取用户对象
        mainOrder.setStatus(3);
        List<MainOrder> list=mainOrderService.getZongCount(mainOrder);
        double zongjine=0;
        if(admin.getAdminId()==1){
            for(MainOrder mo:list){
                zongjine+=mo.getTotalPrice();
            }
        }else{
            for(MainOrder mo:list){
                Integer skuId=mo.getSkuId();    //skuId
                Sku sku=skuService.getSkuById(skuId);   //sku对象
                Integer sessionId=sku.getSessionId(); // 场次id
                Commoditysession commoditysession=commoditysessionService.getById(sessionId);   //获取场次对象
                Integer placeId=commoditysession.getPlaceId();  //场地id
                Place place=placeService.findByPlace(placeId);
                Integer agentId=place.getAgentid();     //代理商id
                /*System.out.println("传入adminId:"+admin.getAdminId()+"查询代理商"+agentId);*/
                if(admin.getAdminId()==agentId){
                    zongjine+=mo.getTotalPrice();
                }
            }
        }
        return zongjine;
    }


    /**
     * 进入主页
     * @return
     */
    @RequestMapping(value = "/zhuye")
    public String ha02(){
        return "shops_index";
    }


    /**
     * 进入省统计图页面
     * @return
     */
    @RequestMapping(value = "/chinaStat")
    public String chinaStat(){
        return "Order_Chart";
    }


    /**
     * 进入商品销售统计页面
     */
    @RequestMapping(value = "/productStat")
    public String productStat(){
        return "Product_Stat";
    }

    /**
     * 进入首页
     */
    @RequestMapping(value = "show01")
    public String show01(){
        return "index";
    }



    /**
     * 统计商品销售排行前十
     * 商品编号，商品名称，销售数量
     */
    @RequestMapping("/getShangpinByStat")
    @ResponseBody
    public Object getShangpinByStat(){
        MainOrder mainOrder=new MainOrder();
        mainOrder.setStatus(3);
        //查询的值
        List<MainOrder> mainOrderList=mainOrderService.selectPaiHang(mainOrder);
        //返回的值
        /*Map<Integer,String> result=new HashMap<Integer, String>();*/
        Map<Integer,String> result = new LinkedHashMap<Integer, String>();
        int a=0;
        for(MainOrder mo:mainOrderList){

            Integer skuId=mo.getSkuId();
            Sku sku=skuService.getSkuById(skuId);   //sku对象
            Integer commodityId=sku.getCommdityId();    //商品id
            Commodity commodity =commodityService.getCommodityById(commodityId);    //商品对象
            String commodityName=commodity.getCommodityName();      //商品名称

            if(result.get(commodityId)==null){
                a=0;
               result.put(commodityId,"");
            }
            result.put(commodityId,commodityId+","+commodityName+","+(++a));

        }

        //map集合根据值排序
        result.entrySet().parallelStream()
                .sorted(Comparator.comparingInt(entry -> Integer.parseInt(((Map.Entry<Integer, String>) entry).getValue().split(",")[2])).reversed())
                .forEachOrdered(entry -> result.put(entry.getKey(), entry.getValue()));


        for (String employee : result.values()) {
            System.out.println(employee);
        }


        /*System.out.println("返回数量："+result.size());*/

        return result;
    }




    /**
     * 统计所有省的销售额,sku，价格
     */
    @RequestMapping("/getSumBySheng")
    @ResponseBody
    public Map<String,Double> getSumBySheng(){
        MainOrder mainOrder=new MainOrder();
        List<MainOrder> mainOrderList=mainOrderService.selectPaiHang(mainOrder);

        Map<String,Double> result=new HashMap<>();

        for(MainOrder mo:mainOrderList){
            Double money=mo.getTotalPrice();
            Integer skuId=mo.getSkuId();
            Sku sku=skuService.getSkuById(skuId);   //获取sku对象
            Integer commodityId=sku.getCommdityId();    //商品id
            Commodity commodity =commodityService.getCommodityById(commodityId);    //商品对象
            City city=cityService.getCityByid(commodity.getProvinceId());     //城市对象
            String cityName=city.getCityName();     //城市名

            if(result.get(cityName)==null){
                result.put(cityName,0.0);
            }
            result.put(cityName,result.get(cityName)+money);
        }

        return result;
    }

}
